﻿using BXS.API.Extensions;
using BXS.API.Middleware;
using Serilog;

namespace BXS.API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // 添加日志服务
            builder.Services.AddLoggingServices(builder.Configuration);

            // 添加服务到容器
            builder.Services.AddControllers();

            // 添加API文档
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerServices();

            // 添加数据库服务
            builder.Services.AddDatabaseServices(builder.Configuration);

            // 添加缓存服务
            builder.Services.AddCacheServices(builder.Configuration);

            // 添加认证服务
            builder.Services.AddAuthenticationServices(builder.Configuration);

            // 添加授权服务
            builder.Services.AddAuthorization();

            // 添加CORS服务
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", policy =>
                {
                    policy
                        .AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });

            // 添加业务服务
            builder.Services.AddBusinessServices();

            var app = builder.Build();

            // 配置HTTP请求管道
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "白喜事API v1");
                    c.RoutePrefix = string.Empty; // 设置Swagger UI为根路径
                });
            }

            // 使用全局异常处理中间件
            app.UseMiddleware<GlobalExceptionHandler>();

            app.UseHttpsRedirection();

            // 使用CORS
            app.UseCors("AllowAll");

            // 使用认证
            app.UseAuthentication();

            // 使用授权
            app.UseAuthorization();

            // 映射控制器
            app.MapControllers();

            // 添加健康检查端点
            app.MapGet("/health", () => Results.Ok(new { Status = "Healthy", Timestamp = DateTime.UtcNow }));

            try
            {
                Log.Information("启动白喜事API服务");
                app.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "服务启动失败");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}
